package com.uziot.bucket.mongodb.config;

import com.mongodb.ConnectionString;
import com.mongodb.MongoClientSettings;
import com.mongodb.MongoDriverInformation;
import com.mongodb.client.MongoClient;
import com.mongodb.client.internal.MongoClientImpl;
import com.uziot.bucket.mongodb.config.props.MultipleMongoProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;

/**
 * @author shidt
 * @version V1.0
 * @className MultipleMongoConfig
 * @date 2020-12-05 22:37:29
 * @description
 */
@Configuration
public class MultipleMongoConfig {

    @Autowired
    private MultipleMongoProperties mongoProperties;

    @Primary
    @Bean(name = "primaryMongoTemplate")
    public MongoTemplate primaryMongoTemplate() {
        return new MongoTemplate(primaryFactory(this.mongoProperties.getPrimary()));
    }

    @Bean
    @Qualifier("secondaryMongoTemplate")
    public MongoTemplate secondaryMongoTemplate() {
        return new MongoTemplate(secondaryFactory(this.mongoProperties.getSecondary()));
    }

    @Bean
    @Primary
    public SimpleMongoClientDatabaseFactory primaryFactory(MongoProperties mongo) {
        String uri = mongoProperties.getPrimary().getUri();
        MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString(uri))
                .build();
        MongoDriverInformation driverInformation = MongoDriverInformation.builder().build();
        MongoClient client = new MongoClientImpl(mongoClientSettings, driverInformation);
        return new SimpleMongoClientDatabaseFactory(client, mongoProperties.getPrimary().getDatabase());
    }

    @Bean
    public SimpleMongoClientDatabaseFactory secondaryFactory(MongoProperties mongo) {
		String uri = mongoProperties.getPrimary().getUri();
		MongoClientSettings mongoClientSettings = MongoClientSettings.builder()
                .applyConnectionString(new ConnectionString(uri))
                .build();
		MongoDriverInformation driverInformation = MongoDriverInformation.builder().build();
		MongoClient client = new MongoClientImpl(mongoClientSettings, driverInformation);
		return new SimpleMongoClientDatabaseFactory(client, mongoProperties.getSecondary().getDatabase());
    }



}